﻿#include "YCameraWidget.h"


#include <QStyleOption>
#include <QPainter>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QDebug>
#include <QListWidget>
#include "../task/YDemuxerTask.h"
#include "../task/YDecoderTask.h"
#include "YCameraConfig.h"
//渲染
void YCameraWidget::paintEvent(QPaintEvent* p)
{
	//渲染样式表
	QStyleOption opt;
	opt.init(this);
	QPainter painter(this);
	style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
}
YCameraWidget::YCameraWidget(QWidget* p) :QWidget(p)
{
	//接收拖拽
	this->setAcceptDrops(true);
}

//拖拽进入
void YCameraWidget::dragEnterEvent(QDragEnterEvent* e)
{
	//接收拖拽进入
	e->acceptProposedAction();
}

void YCameraWidget::dragMoveEvent(QDragMoveEvent* e)
{
	//if (e->mimeData()->hasText() || e->mimeData()->hasUrls()) {
		e->setDropAction(Qt::CopyAction);
		e->accept();
	//}
	//else {
		//e->ignore();
	//}
}

//拖拽松开
void YCameraWidget::dropEvent(QDropEvent* e)
{
	//拿到url
	qDebug() << e->source()->objectName();
	auto wid = (QListWidget*)e->source();
	qDebug() << wid->currentRow();
	auto cam = YCameraConfig::Create()->GetCamera(wid->currentRow());
	Open(cam.sub_url);

}

//渲染视频
void YCameraWidget::Draw()
{
	if (!demux_ || !decode_ || !view_)return;
	auto f = decode_->GetFrame();
	if (!f)return;
	view_->DrawFrame(f);
	YFreeFrame(&f);
}

void YCameraWidget::Stop()
{
	if (view_)
	{
		view_->Close();
		delete view_;
		view_ = nullptr;
	}
	if (decode_)
	{
		decode_->Stop();
		delete decode_;
		decode_ = nullptr;
	}
	if (demux_)
	{
		demux_->Stop();
		delete demux_;
		demux_ = nullptr;
	}
}


bool YCameraWidget::Open(const char* url)
{
	if (demux_)
		demux_->Stop();
	if (decode_)
		decode_->Stop();
	//打开解封装线程
	demux_ = new YDemuxerTask();
	if (!demux_->Open(url))
	{
		return false;
	}
	//打开视频解码器线程
	decode_ = new YDecoderTask();
	auto para = demux_->CopyVideoPara();
	if (!decode_->Open(para->para))
	{
		return false;
	}
	//设定解码线程接收解封装数据
	demux_->setNext(decode_);

	//初始化渲染参数
	view_ = IVideoRenderView::Create();

	int videoWidth = demux_->getWidth();;
	int videoHeight = demux_->getHeight();
	view_->Init(videoWidth, videoHeight, IVideoRenderView::YUV420P, (void*)winId());

	//启动解封装和解码线程
	demux_->Start();
	decode_->Start();
	return true;
}


//清理资源
YCameraWidget::~YCameraWidget()
{
	/*if (demux_)
	{
		demux_->Stop();
		delete demux_;
		demux_ == nullptr;
	}
	if (decode_)
	{
		decode_->Stop();
		delete decode_;
		decode_ == nullptr;
	}
	if (view_)
	{
		view_->Close();
		delete view_;
		view_ = nullptr;
	}*/
	//Stop();
}


